#include "EngineHeader.h"

namespace LSH
{

//------------------------------------------------------------------------
Timer::Timer()
{
    _usingQPF = false;
    _ticksPerSec = 0;
    _baseTime = 0;
    _stopTime = 0;
    _initialize();
}

//------------------------------------------------------------------------
Timer::~Timer(){
}

//------------------------------------------------------------------------
TimeValue Timer::start()
{
    LONGLONG nowTime = _getTicks();
    if(_stopTime != 0)
    {
        _baseTime += nowTime - _stopTime;
        _stopTime = 0;
    }
    else
    {
        _baseTime = nowTime;
    }
    TimeValue interval = (nowTime - _baseTime) / (TimeValue)_ticksPerSec;
    return interval;
}

//------------------------------------------------------------------------
TimeValue Timer::stop()
{
    LONGLONG nowTime = _getTicks();
    _stopTime = nowTime;
    TimeValue interval = (nowTime - _baseTime) / (TimeValue)_ticksPerSec;
    return interval;
}

//------------------------------------------------------------------------
void Timer::reset()
{
    LONGLONG nowTime = _getTicks();
    _baseTime = nowTime;
    _stopTime = 0;
}

//------------------------------------------------------------------------
TimeValue Timer::getTime()
{
    LONGLONG nowTime = 0;
    if(_stopTime == 0)
    {
        nowTime = _getTicks();
    }
    else
    {
        nowTime = _stopTime;
    }
    TimeValue interval = (nowTime - _baseTime) / (TimeValue)_ticksPerSec;
    return interval;
}

//------------------------------------------------------------------------
TimeValue Timer::getAbsoluteTime()
{
    LONGLONG nowTime = _getTicks();
    TimeValue absoluteTime = nowTime / (TimeValue)_ticksPerSec;
    return absoluteTime;
}

//------------------------------------------------------------------------
void Timer::_initialize()
{
    LARGE_INTEGER qwTicksPerSec;
    BOOL ret = QueryPerformanceFrequency( &qwTicksPerSec );
    _usingQPF = (ret == TRUE) ? true : false;
    if(_usingQPF)
    {
        _ticksPerSec = qwTicksPerSec.QuadPart;
    }
    else
    {
        _ticksPerSec = 1000; 
    }
}

//------------------------------------------------------------------------
LONGLONG Timer::_getTicks()
{
    if(_usingQPF)
    {
        LARGE_INTEGER qwTime;
        QueryPerformanceCounter(&qwTime);
        return qwTime.QuadPart;
    }
    else
    {
        return (LONGLONG)timeGetTime();
    }
}

}   // LSH
